;(function($){
	$.widget("tempo.columnselect",{
		options:{
			width:270,
			height:300,
			hideToolBar:false,//是否隐藏选择按钮工具条
			data:[],
			showRadios:[],// 可选参数，显示指定类型的单选按钮，如只显示字符，选项有all,string,number,timestamp,text,tempo_vector
			udfSearch:function(itemData){
				// 可选参数，若需要在类型过滤的同时，再添加其他过滤条件，可覆盖该属性,thisEle为待选列表中的一项
				// 返回true（满足条件）或false（不满足条件）
				return true;
			},
			placeholder:TempoUtils.locale("mine.sousuziduanming"),
		},
		_create:function(){
			this.element.addClass("tempo-columnselect").css({
				'width':this.options.width,
				'height':this.options.height
				});
			
			var columnSelectLeftDiv = $('<div/>',{"class":"tempo-columnselect-left"}).appendTo(this.element);
			var parentDiv = $('<div/>').addClass("tempo-columnselect-datatype");
			// 第一个单选按钮组件，初始化完成后，调用click事件选中第一个，不能用checked属性设置选中，有浏览兼容问题
			var firstRaio;
			// 若showRadios的长度为空，则显示全部
			// 记录radio个数，若超过3个，则会换行，需要修改tempo-mine-column-field的高度
			var radioNum = 0;
			if (this.options.showRadios.length == 0){
				firstRaio = this._appendTypeRadio('all',parentDiv);
				this._appendTypeRadio('string',parentDiv);
				this._appendTypeRadio('number',parentDiv);
				parentDiv.append($('<br/>'));
				this._appendTypeRadio('timestamp',parentDiv);
				this._appendTypeRadio('text',parentDiv);
				radioNum = 5;
			} else {
				for (var i=0;i<this.options.showRadios.length;i++){
					//日期和日期时间 统一用日期时间处理
					if(this.options.showRadios[i]=="datetime"){
						continue;
					}
					var radioEle = this._appendTypeRadio(this.options.showRadios[i],parentDiv);
					if (i == 2) {
						parentDiv.append($('<br/>'));
					}
					if (i == 0){
						firstRaio = radioEle;
					}
				}
				radioNum = this.options.showRadios.length;
			}
			
			parentDiv.appendTo(columnSelectLeftDiv);
		
			var search=$('<div/>').addClass("tempo-column-search")
			.appendTo(columnSelectLeftDiv);
			
			var sourceLayout = $('<div/>').addClass("tempo-mine-column-field").appendTo(columnSelectLeftDiv);
			search.searchbar({
				placeholder:this.options.placeholder,
				auto:true,
				onSearch:function(data){
					sourceLayout.find("li").each(
						function() {
							thisObj._combineSearch($(this));
						});
				}
			});
			
			var data = this.options.data;
			var ul = $('<ul/>').addClass("tempo-mine-column-list").
						attr("id","_column_container").appendTo(sourceLayout);
			this.options.ul = ul;
			if (data.length > 0) {
				for (var i=0;i<data.length;i++) {
					
					$("<li/>").data("data",data[i]).html(data[i].desc).attr("title", data[i].name?data[i].name:data[i].desc).appendTo(ul);
				}
			}
			var thisObj=this;
			var addToolBar = function (){
				$('<div/>').addClass("tempo-columnselect-dataselect")
				.append($("<div class='tempo-columnselect-allselect'><button id='allselect' name='columnselect'></button></div>"))
				.append($("<div class='tempo-columnselect-right-remove'><button id='tempo-columnselect-right-remove-btn'></button></div>"))
				.append($("<div class='tempo-columnselect-left-remove'><button id='tempo-columnselect-left-remove-btn'></button></div>"))
				.append($("<div class='tempo-columnselect-reverseselect'><button id='reverseselect' name='columnselect'></button></div>"))
				.appendTo(thisObj.element);
			}
			
			if(!this.options.hideToolBar){
				addToolBar();
			} else {
				// 不添加工具按钮，则设置宽度占满
				columnSelectLeftDiv.css({"width":"100%"});
			}
			
			this.element.find('input[name=dataselect]').unbind('click').bind("click",function(e) {
				$(this).attr('checked',true);
		        ul.find("li").each(function() {
		        	thisObj._combineSearch($(this));
		        });
			});
			this._bindEvent(ul);
			sourceLayout.unbind('click').bind('click',function() {
			});
			// 高度修改，先计算出list的外边距
			var outer = sourceLayout.outerHeight(true) - sourceLayout.height();
			sourceLayout.height(this.element.innerHeight() - this.element.find('.tempo-columnselect-datatype').outerHeight(true)
						- this.element.find('.tempo-column-search').outerHeight(true) - outer - 5);
			// 选中第一个单选按钮
			firstRaio.click();
		},
		_setOption:function(key,val){
		},
		_bindEvent:function(ul) {
			ul.find('li').unbind('mousedown').bind('mousedown',function(e) {
				var e = e||window.event;
				e.preventDefault();
				var that = $(this);
				if (e.button == 0) {
					if (e.ctrlKey) {
						that.toggleClass('tempo-mine-column-backgroundcolor');
					} else if (e.shiftKey) {
						var selectedIndex=-1;
						var maxInternal=Number.MIN_VALUE;
						that.siblings().each(function() {
							if ($(this).hasClass('tempo-mine-column-backgroundcolor')) {
								if (Math.abs(that.index()-$(this).index()) > maxInternal) {
									maxInternal = Math.abs(that.index()-$(this).index());
									selectedIndex = $(this).index();
								}
							}
						});
						
						if (selectedIndex != -1) {
							var startIndex;
							var endIndex;
							if (selectedIndex < that.index()) {
								startIndex = selectedIndex;
								endIndex = that.index();
							} else {
								startIndex = that.index();
								endIndex = selectedIndex;
							}
							ul.find('li').each(function(i){
								if (i >=startIndex &&　i <=  endIndex) {
									$(this).addClass('tempo-mine-column-backgroundcolor');
								}
							});
		
						} else {
							startIndex = 0;
							endIndex = that.index();
							ul.find('li').each(function(i){
								if (i >=startIndex &&　i <=  endIndex) {
									$(this).addClass('tempo-mine-column-backgroundcolor');
								}
							});
						}
					} else {
						that.addClass('tempo-mine-column-backgroundcolor');
						that.siblings().removeClass('tempo-mine-column-backgroundcolor');
					}
				}
			});
		},
		addRowData:function(data, needBindAll) {
			var ul = this.options.ul;
			var curLi = $('<li/>').data("data",data).html(data.desc).attr("title", data.name?data.name:data.desc).appendTo(ul);
			curLi.addClass("nodisplay");
			var dataSelectId = this.element.find('input[name=dataselect]:checked').attr("id") || "all";
			var type = data.type;
			if (type && dataSelectId == 'number' && TempoMineMetaUtils.isNumber(type.toUpperCase())) {
				curLi.removeClass("nodisplay");
    		} else if(type && dataSelectId=="timestamp"&&(type.toUpperCase() == dataSelectId.toUpperCase()||type.toUpperCase()=="DATETIME")){
				curLi.removeClass("nodisplay");
			} else if (type && type.toUpperCase() == dataSelectId.toUpperCase()) {
    			curLi.removeClass("nodisplay");
    		} else if (dataSelectId == 'all'){
    			curLi.removeClass("nodisplay");
    		}
			// 未设置needBindAll，默认绑定数据
			if (undefined == needBindAll || null == needBindAll){
				this._bindEvent(ul);
			}
		},
		bindAllDataEvent:function(){
			// 给所有数据绑定事件
			this._bindEvent(this.element.find(".tempo-mine-column-list"));
		},
		_appendTypeRadio:function(radioId,parentDiv) {
			// 添加radio到指定div上，并返回radio
			var radioLabel = "";
			var radioLabelTitle = "";
			if (radioId == "string"){
				radioLabel = TempoUtils.locale('mine.character');
				radioLabelTitle = TempoUtils.locale('mine.charactertitle');
			} else if (radioId == "timestamp"){
				radioLabel = TempoUtils.locale('mine.date');
				radioLabelTitle = TempoUtils.locale('mine.datetitle');
			} else if (radioId == "tempo_vector"){
				radioLabel = TempoUtils.locale('mine.meta_fields_label_tempo_vector');
				radioLabelTitle = TempoUtils.locale('mine.meta_fields_label_tempo_vectortitle');
			} else {
				radioLabel = TempoUtils.locale('mine.'+radioId);
				radioLabelTitle = TempoUtils.locale('mine.'+radioId+'title');
			}
			var radioEle = $('<input/>',{
				'type':'radio',
				'name':'dataselect',
				'class':"tempo-radio",
				'id':radioId,
			});
			var labelObj = $('<label for="'+radioId+'">'+radioLabel+'</label>');
			labelObj.attr("title",radioLabelTitle);
			parentDiv.append(radioEle).append(labelObj);
			return radioEle;
		},
		_combineSearch:function(columnSelectEle){
			// 类型单选与查询框条件进行组合查询
			var type = columnSelectEle.data("data").type || "";
			if(type && type == "DATETIME"){
				type = "TIMESTAMP";
			}
        	var searchText = this.element.find(".tempo-searchbar-searthinput").val().toUpperCase();
        	var id = this.element.find("input[name='dataselect']:checked").attr("id");
        	var thisText = columnSelectEle.html().toUpperCase();
        	var showRadios = this.options.showRadios;
        	// 若自定义判断方法存在，且当前项不满足条件，则设置为不可见并返回
        	if (!this.options.udfSearch(columnSelectEle.data("data"))){
        		columnSelectEle.addClass("nodisplay");
        		return;
        	}
        	if (searchText && searchText != "" && thisText.indexOf(searchText) == -1){
        		// 校验当前内容是否与搜索框内容（不为空串）匹配
        		columnSelectEle.addClass("nodisplay");
        	} else if (id == 'all') {
        		if (showRadios.length == 0){
        			// 若自定义显示类型为空，且当前显示的类型为全部类型，则过滤向量类型，显示其他所有类型
        			if (TempoMineMetaUtils.isVector(type.toUpperCase())){
        				// 向量类型默认隐藏
        				columnSelectEle.addClass("nodisplay");
        			} else {
        				columnSelectEle.removeClass("nodisplay");
        			}
        		} else {
        			// 否则，判断当前类型是否在当前设置的显示类型中
        			var findFlag = false;
        			for (var i=0;i<showRadios.length;i++){
        				if (showRadios[i].toUpperCase() == type.toUpperCase()){
        					columnSelectEle.removeClass("nodisplay");
        					findFlag = true;
        					break;
        				} else if (showRadios[i] == "number" && TempoMineMetaUtils.isNumber(type.toUpperCase())){
        					columnSelectEle.removeClass("nodisplay");
        					findFlag = true;
        					break;
        				}
        			}
        			if (!findFlag){
        				columnSelectEle.addClass("nodisplay");
        			}
        		}
        	} else if (id == 'number') {
               	if (TempoMineMetaUtils.isNumber(type.toUpperCase())) {
               		columnSelectEle.removeClass("nodisplay");
            	} else {
            		columnSelectEle.addClass("nodisplay");
            	}
        	}else {
            	if (type.toUpperCase() == id.toUpperCase()) {
            		columnSelectEle.removeClass("nodisplay");
            	} else {
            		columnSelectEle.addClass("nodisplay")
            	}
        	}
		}
	});
})(jQuery)